package com.example.hobbyplanetserve.controller;

import com.example.hobbyplanetserve.Result.Result;
import com.example.hobbyplanetserve.dto.DtoLogin;
import com.example.hobbyplanetserve.entity.MyTUserDetail;
import com.example.hobbyplanetserve.entity.User;
import com.example.hobbyplanetserve.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
@CrossOrigin
@Slf4j
public class UserController {

    @Resource
    private UserService userService;


    /**
     * 用户登陆
     * @param dtoLogin
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody DtoLogin dtoLogin) {
        log.info("Login Page Username :{}  password {}", dtoLogin.getUsername(), dtoLogin.getPassword());
        //登陆业务
        String token = userService.login(dtoLogin);
        if (token != null) {
            return Result.ok().data("token",token);
        }else{
            return Result.error();
        }
    }

    /**
     * 获取当前用户信息
     * @return
     */
    @GetMapping("/current")
    public Result getCurrentUser() {
        MyTUserDetail userDetail = (MyTUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        log.info("获取到的用户信息为：{}", userDetail);
        return Result.ok().data("user", userDetail);
    }


    @GetMapping("/list")
    public List<User> getList() {
        return userService.list();
    }

    @PostMapping("/add")
    public boolean add(@RequestBody User user) {
        userService.saveUser(user);
        return true;
    }
}
